<?php

namespace app\api\controller;

use app\common\controller\Api;

use app\common\model\Banner;
use app\common\model\CateGoods;
use app\common\model\Goods;
use http\Env\Request;
use think\Db;

/**
 * 首页接口
 */
class Index extends Api
{
    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];


    /**
     * 首页
     *
     */
    public function index()
    {
        $data = model('index')->indexInfo();
        $this->success('请求成功', $data);
    }

    /*
     * 会员说明
     * */
    public function vip()
    {
        $data = model('vip')->info();
        $this->success('查询成功', $data);
    }

    /*
     * 协议
     * */
    public function agreement()
    {
        $data = model('index')->agreements();
        $this->success('查询成功', $data);
    }

    /*
     * 地区
     * */
    public function area()
    {
        $data = model('index')->areas();
        $this->success('查询成功', $data);
    }

    /*
     * 秒杀商品
     * */
    public function seckill()
    {
        // 获取信息
        $data = $this->request->param('request_data');
        $data_json = base64_decode($data); //数据解密
        $data_array = json_decode($data_json, true);
        $data = model('index')->seckills($data_array);
        $this->success('查询成功', $data);
    }


    /*
    * 定期返回金额
    * */
    public function regular()
    {
        $time = time();// 获取现在时间
        $config = Db::name('config')->where('id', 28)->value('value');
        $config = explode(',', $config);
        // 现在时间大于特定的时间
        $new = strtotime(date('Y-m-d 12:00:00', $time));
        // 获取用户的金额
        $refund = Db::name('user_refund_amount')->select();
        // $refund = Db::name('user_refund_amount')->where("user_id",85)->select();
        // 获取现在的时间
        $firstday = date("Y-m-d", $time);
        // 第几天
        $day = date('d');
        // 天数 大于 现在的天数
        if ($config[0] > $day || $config[0] == $day) {
            // 获取下月的某一天时间
            $firstdays = strtotime(date("Y-m-01 12:00:00", strtotime("$firstday +0 month"))) + $config[0] * 86400 - 86400;
        } else {
            // 获取下月的某一天时间
            $firstdays = strtotime(date("Y-m-01 12:00:00", strtotime("$firstday +1 month"))) + $config[0] * 86400 - 86400;
        }
        // $firstdays = 1698292800;
        $user = Db::name('user')->where(['is_vip' => 1])->field('id')->column('id,id as user_id');
        // $user = Db::name('user')->where(['is_vip'=>1])->where("id",85)->field('id')->column('id,id as user_id');
        foreach ($refund as $key => $val) {
            // 截取字符串
            $str = substr($config[1], 0, strrpos($config[1], '%'));
            // 现在时间 == 规定时间 返回金额
            if ($new == $firstdays) {
                if (isset($user[$val['user_id']])) {
                    // 为空时，第一次返回金额
                    if (empty($val['refund_amount'])) {
                        $money = $val['money'] * $str / 100;
                        Db::name('user')->where(['id' => $val['user_id']])->setInc('money', $money);
                        Db::name('user_refund_amount')->where('id', $val['id'])->setInc('refund_amount', $money);
                        $consume = [
                            'user_id' => $val['user_id'],
                            'sub_user_id' => 0,
                            'type' => 1,
                            'status' => 1,
                            'money' => $money,
                            'content' => '返还的金额',
                            'create_time' => time()
                        ];
                        Db::name('user_consume')->insert($consume);
                    } else {
                        $money = ($val['money'] - $val['refund_amount']) * $str / 100;
                        if ($money > 0.01) {
                            // 之前的金额大于现在金额
                            if ($val['money'] >= $money) {
                                Db::name('user')->where('id', $val['user_id'])->setInc('money', $money);
                                Db::name('user_refund_amount')->where('id', $val['id'])->setInc('refund_amount', $money);
                                $consume = [
                                    'user_id' => $val['user_id'],
                                    'sub_user_id' => 0,
                                    'type' => 1,
                                    'status' => 1,
                                    'money' => $money,
                                    'content' => '返还的金额',
                                    'create_time' => time()
                                ];
                                Db::name('user_consume')->insert($consume);
                            }
                        }
                    }
                }
            }
        }
    }


    /*
     * 订单定时取消状态
     * */
    public function statusOrder()
    {
        $time = time();
        $data = Db::name('order')->where('status', 1)->select();
        foreach ($data as $val) {
            // 现在时间大于10分钟
            if ($time - $val['create_time'] >= 600) {
                // 订单状态：取消
                Db::name('order')->where('id', $val['id'])->update(['status' => 7]);
            }
        }
    }

    /*
     * 是否会员过期
     * */
    public function vipTime()
    {
        $data = Db::name('user_vip')->where(['status' => 2, 'is_delete' => 1])->select();
        // print_r($data);exit;
        $id = $ids = [];
        if ($data) {
            foreach ($data as $val) {
                if ($val['end_time'] <= time()) {
                    $id[] = $val['user_id'];
                    $ids[] = $val['id'];
                }
            }
        }
        if (count($id)) {
            $id = implode(',', $id);
            $ids = implode(',', $ids);
            Db::name('user')->where('id', 'in', $id)->update(['is_vip' => 0]);
            Db::name('user_vip')->where('id', 'in', $ids)->update(['is_delete' => 2]);
        }

    }


    /*
     * 定时确认收货
     *
     * */
    public function confirm()
    {
        // 获取第几天收货
        $config = Db::name('config')->where('id', 33)->value('value');
        $time = time();
        $order = Db::name('order')->where('status', 3)->field('id,title,user_id,num,goods_id,order_id,create_time')->select();
        foreach ($order as $val) {
            if ($val['create_time'] + ($config * 86400) <= $time) {
                model('User')::item($val['user_id'], $val['order_id']);
                Db::name('order')->where('id', $val['id'])->update(['logistics_time' => time(), 'status' => 5]);
                $item = Db::name('goods')->where('id', $val['goods_id'])->value('item');
                $item = json_decode($item, true);
                $intro = [];
                foreach ($item as $va) {
                    if ($val['title'] == $va['title']) {
                        $intro[] = $va['integral'];
                    }
                }
                $money = array_sum($intro) * $val['num'];
                // 计算积分，返还积分
                $con = ['user_id' => $val['user_id'], 'sub_user_id' => 0, 'type' => 2, 'status' => 1, 'money' => $money, 'content' => '返还爱心值', 'create_time' => time()];
                // 生成记录
                Db::name('user_consume')->insert($con);
                // 增加爱心值
                Db::name('user')->where('id', $val['user_id'])->setInc('score', $money);
            }
        }
    }

    // 秒杀商品
    public function killShop()
    {
        // 规格名称
        $norms = "5斤";
        $redis = new \Redis();
        //连接
        $redis->connect('127.0.0.1', 6379);
        $uid = mt_rand(1, 9999);

        $goods_id = 6;
        $key = 'list_seckill_goods_id_' . $goods_id;

        $item = Db::name('goods')->where('id', $goods_id)->value('item');
        $item = json_decode($item, true);
        foreach ($item as $keys => $val) {
            if ($norms == $val['title']) {
                if ($val['stock'] == 0) return ['code' => '0', 'msg' => '库存不足', 'data' => ''];
                $item[$keys]['stock'] = $val['stock'] - 1;
            }
        }

        // 从链表的头部删除一个元素，返回删除的元素,因为pop操作是原子性，即使很多用户同时到达，也是依次执行
        $count = $redis->lpop($key);
        if (!$count) {
            return '已抢光！';
        }

        //已抢购用户id队列
        $userListKey = 'user_goods_id_' . $goods_id;
        //判断该用户是否已经抢购过
        //该用户id是否在抢购用户集合中
        $userBuyStatus = $redis->sismember($userListKey, $uid);
        if ($userBuyStatus) {
            return '您已抢过！';
        }

        //将用户id添加到抢购成功用户集合中
        $redis->sadd($userListKey, $uid);

        $msg = '抢到的人为：' . $uid . '，抢到商品的顺序为第' . $count . '个';
        $redis->lpush('success', $msg);

        //操作数据库，修改商品库存销量
        Db::name('goods')->where('id', $goods_id)->update(['item' => json_encode($item)]);
        //创建订单信息

        return '恭喜您抢购成功！';

    }


    public function getVipGoods()
    {
        $url    = config('fastadmin.api_url');

        $goods = Db::name('cate_goods')->where('pid','>',0)->where('status',1)->field('id,title')->select();
        foreach($goods as $key => &$val)
        {
            if(empty($val['id']))
            {
                $val['goods'] = Db::name('goods')->where(['state'=>2,'type'=>4])->field('id,image,name,integer,money,item,integer')->select();
                foreach($val['goods'] as &$val1)
                {
                    $item = json_decode($val1['item'],true);
                    $item = current($item);
                    $val1['money'] = $item['intro'];
                    $val1['image'] = $url.$val1['image'];
                    !isset($item['vip_money']) ? $val1['vip_money']= 0 : $val1['vip_money']= $item['vip_money'];
                }
            }else{
                $val['goods'] = Db::name('goods')->where(['cate_id'=>$val['id'],'type'=>4])->field('id,image,name,integer,money,item,integer')->select();
                foreach($val['goods'] as &$val1)
                {
                    $item = json_decode($val1['item'],true);
                    $item = current($item);
                    $val1['money'] = $item['intro'];
                    $val1['image'] = $url.$val1['image'];
                    !isset($item['vip_money']) ? $val1['vip_money']= 0 : $val1['vip_money']= $item['vip_money'];
                }
            }
        }

        $this->success('请求成功', ['goods'=>$goods]);
    }


    /*
     * 商品搜索
     */
    public function indexSearch()
    {
        // 获取信息
        $data = $this->request->param('request_data');
        $data_json = base64_decode($data); //数据解密
        $data_array = json_decode($data_json, true);
        $data = model('index')->indexSearch($data_array);
        $this->success('查询成功', $data);
    }

}
